package com.yc.mqtt.handler.message;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;

import java.util.ArrayList;
import java.util.List;

public class MqttSubscribeMessageHandler extends MqttBaseMessageHandler{
    @Override
    public void onMessage(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) {
        MqttSubscribeMessage mqttSubscribeMessage = (MqttSubscribeMessage) mqttMessage;
        MqttFixedHeader respMqttFixedHeader = new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0);
        MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(mqttSubscribeMessage.variableHeader().messageId());
        List<Integer> grantedQoSLevels = new ArrayList<>(mqttSubscribeMessage.payload().topicSubscriptions().size());
        for (int i = 0; i < mqttSubscribeMessage.payload().topicSubscriptions().size(); i++) {
            grantedQoSLevels.add(mqttSubscribeMessage.payload().topicSubscriptions().get(i).qualityOfService().value());
        }
        MqttSubAckPayload payload = new MqttSubAckPayload(grantedQoSLevels);
        MqttSubAckMessage mqttSubAckMessage = new MqttSubAckMessage(respMqttFixedHeader, variableHeader, payload);
        channelHandlerContext.channel().writeAndFlush(mqttSubAckMessage);
    }
}
